﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Globalization;

namespace Statistic
{
    sealed public class SkyWalkerReader : IReader
    {
        int i = 1;

        /**
 * Cleans htmlcode
 * @param url
 *  the html code to be cleaned
 * @param first
 *  from..
 * @param second
 *   to..
 * @return result_
 *   The html code cleaned
 */
        public static string CleanSource(string source, string first, string second)
        {
            string cleanedSource = "";
            try
            {
                int firstChr = source.IndexOf(first, StringComparison.OrdinalIgnoreCase);
                int lastChr = source.IndexOf(second, StringComparison.OrdinalIgnoreCase);
                int length = lastChr - firstChr;
                string strTemp = source.Substring(firstChr, length);
                cleanedSource = strTemp.Remove(0, 6);
            }
            catch (ArgumentOutOfRangeException)
            {
                cleanedSource = "";
            }
            return cleanedSource;
        }

        /**
        * Converts date to the correct format
        * @param result
        * @return result
        *  correct date format
        */
        private static DateTime GetDate(string result, string message)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR", true);
            string url = "";
            int FirstChr = result.IndexOf(message, StringComparison.OrdinalIgnoreCase);          
            DateTime dateTime;
            try
            {
                int FirstChr1 = result.Length - 1;
                int yo = FirstChr1 - FirstChr;
                string strTemp = result.Substring(FirstChr, yo);
                url = CleanSource(strTemp, "advertValues" + "\"" + ">", "</span>");
                result = url.Remove(0, 9);

                dateTime = DateTime.Parse(result, CultureInfo.CurrentCulture);
            }
            catch (ArgumentOutOfRangeException)
            {
                dateTime = DateTime.Now; 
            }
            catch (FormatException)
            {
                dateTime = DateTime.Now;
            }
            return dateTime;
        }

        /**
         * Get all advertisement links
         * @return advs
         *   A list which contains all advertisement links
         */
        IList<string> IReader.GetLinks()
        {
            Protocol statsProtocol = new Protocol();
            IList<string> advs = new List<string>();
            string htmlCode;
            bool continueSearch = true;
            while (continueSearch)
            {               
                for (int k = 2; k < 12; k++)
                {
                    htmlCode = statsProtocol.GetHtmlCode("http://www.skywalker.gr/advertsMenu.aspx?sectorID=15&fromRow=" + i);
                    string SearchString = "ctl00_masterContent_advertsGridView_ctl0"+k+"_titleLinkButton";
                    if (k >= 10)
                    {
                        SearchString = "ctl00_masterContent_advertsGridView_ctl" + k + "_titleLinkButton";
                    }

                    int firstChr = htmlCode.IndexOf(SearchString, StringComparison.OrdinalIgnoreCase);
                    if (firstChr == -1)
                    {
                        break;
                    }
                    int lastChr = htmlCode.Length - 1;
                    int yo = lastChr - firstChr;
                    string cuttedHtmlCode = htmlCode.Substring(firstChr, yo);
                    string cleanedHtmlCode = CleanSource(cuttedHtmlCode, "href=" + "\"", "\"" + ">");
                    string newUrl = "http://www.skywalker.gr/" + cleanedHtmlCode;
                    advs.Add(newUrl);
                }
                i = i + 10;
                htmlCode = statsProtocol.GetHtmlCode("http://www.skywalker.gr/advertsMenu.aspx?sectorID=15&fromRow=" + i);
                continueSearch = HtmlString.PageExists(htmlCode, "advertPageLinkCurrentClass'>1<");
            }
            return advs;
        }

        IList<Advertisements> IReader.DoTheWork()
        {
            Protocol statsProtocol = new Protocol();
            IList<string> advs = new List<string>();
            IList<Advertisements> advsResult = new List<Advertisements>();
            IReader reader = new SkyWalkerReader();
            advs = reader.GetLinks();

            for (int i = 0; i < advs.Count; i++)
            {
                Advertisements advertisements = new Advertisements();
                string htmlCode = statsProtocol.GetHtmlCode(advs[i].ToString());
                string cleanedhtmlCode = CleanSource(htmlCode, "<ul>", "<tr><td valign=" + "\"" + "bottom" + "\"" + ">&nbsp;</td></tr>");
                cleanedhtmlCode = HtmlString.StripTagsCharArray(cleanedhtmlCode);
                advertisements.Content = cleanedhtmlCode;
                DateTime date = GetDate(htmlCode, "Ημερομηνία δημοσίευσης/ανανέωσης:");
                advertisements.Date = date;
                advsResult.Add(advertisements);
            }
            return advsResult;
        }
    }
}
